
package response;

import PolladminFunc.PollDAO;
import bean.PollUser;
import bean.Question;

import com.turningtech.poll.Poll;
import com.turningtech.poll.PollService;
import com.turningtech.poll.Poll.PollingMode;
import com.turningtech.poll.Response;
import com.turningtech.poll.ResponseListener;
import com.turningtech.receiver.Receiver;
import com.turningtech.receiver.ReceiverService;
import com.turningtech.receiver.ResponseCardLibrary;

import connection.DbConnection;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.ArrayList; 
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import model.PollUserImpl;

import org.jfree.data.category.DefaultCategoryDataset;
import java.sql.*;

/**
 * Test app for demoing ResponseCard(C) SDK capabilities.
 *
 * @author Turning Technologies
 */
public class ResponseCardInterface extends javax.swing.JFrame {
	
	private static final long serialVersionUID = 5866141474251384112L;
	private Poll poll;
    private ResponseListModel responseListModel = new ResponseListModel();
    private ReceiverListModel receiverListModel = new ReceiverListModel();
    private ReceiverListCellRenderer receiverCellRenderer = new ReceiverListCellRenderer();
    //dataset for poll results graph
    private DefaultCategoryDataset dataset;
    private  DbConnection conn = new DbConnection();
    private String username;

    public ResponseCardInterface() throws SQLException {
        initReceivers();
        initComponents();
        initModel();
        jPopupMenu1.add(new SetChannelAction());
        if (receiverList.getModel().getSize() > 0)
            receiverList.setSelectedIndex(0);
        //adding default polling option
        JMenuItem jMenuItemPoll = new JMenuItem();
        jMenuItemPoll.setText("SingleResponse");
        jMenuItemPoll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        
        //testing stuff
        login("pm","pass");
        System.out.println(username);
        ArrayList<String[]> mps = getMasterPolls();
        int examplePoll = -1;
        System.out.println("MASTER'S POLLS:");
        System.out.println("/////////");
        for(String[] a : mps){
        	System.out.println(a[1]);
        	examplePoll = Integer.parseInt(mps.get(0)[0]);
        	
        }
        System.out.println("/////////");
        System.out.println("get poll #"+examplePoll+" questions:");
        System.out.println(".........");
        ArrayList<String> questions = getPollQuestions(examplePoll);
        int exampleQuestion = -1;
        for(String s : questions){
        	System.out.println(s);
        	exampleQuestion = Integer.parseInt(s);
        }
        System.out.println(".........");
        System.out.println("hasOpenQuestion:");
    		System.out.println(hasOpenQuestion(exampleQuestion));
        System.out.println("OpenPolling:");
        	openPolling(exampleQuestion);
        System.out.println("hasOpenQuestion:");
        	System.out.println(hasOpenQuestion(exampleQuestion));
    }
    
    /**
     * Takes a username and password of the PollMaster, attempts a login
     * If user is not a PollMaster, fails login.
     *	@param username The username of the PollMaster
     *	@param password The password of the PollMaster
     */
    private boolean login(String username, String password){
    	String sql ="SELECT Username, Password, Accessibility FROM PollUser " +
    			"WHERE Accessibility=2 " +
    			"AND Username='"+username+"' " +
    			"AND Password='"+password+"'";
    	boolean login = false;
    	try{
    		PreparedStatement ps = conn.getConn().prepareStatement(sql);
    		ResultSet rs = ps.executeQuery();
    		
    		if(rs.next()){
    			login = true;
    			this.username = rs.getString("Username");
    		}
    		System.out.println("Attempted login:"+login);
    		
    	}catch(Exception e){
    		System.out.println("Login failed!");
    		e.printStackTrace();
    	}
    	return login;
    }
    
    /**
     * Returns a list of polls created by the PollMaster. 
     * !PollMaster must be logged in first!
     * @return an ArrayList of string arrays: each string array contains the pollID, followed by the poll name.
     * @author s4200334
     */
    private ArrayList<String[]> getMasterPolls(){
    	ArrayList<String[]> pollList = new ArrayList<String[]>();
		String sql="SELECT User_Poll.Username, User_Poll.PollID	, PollUser.Username, PollUser.Accessibility, Poll.Name, Poll.ID FROM User_Poll, PollUser, Poll " +
				   "WHERE PollUser.Accessibility = 2 " +
				   "AND PollUser.Username = '"+username+"' " +
				   "AND User_Poll.pollID = Poll.ID " +
				   "AND User_Poll.Username = PollUser.Username";
		try{
			PreparedStatement ps = conn.getConn().prepareStatement(sql);
			ResultSet rs = ps.executeQuery(sql);
			while(rs.next()){
				String[] st = new String[2];
				st[0] = rs.getString("ID");
				st[1] = rs.getString("Name");
				pollList.add(st);
			}
		}catch(Exception e){e.printStackTrace();}
		return pollList;
    }
    
    /**
     * Opens the given question for for responses.
     * @param QuestionID the Question to open
     * @return true if Question opened successfully, else false.
     */
    private boolean openPolling(int QuestionID){
    	String sql = "UPDATE Question SET status=1 WHERE QuestionID="+QuestionID;
    	
    	try{
    		PreparedStatement ps = conn.getConn().prepareStatement(sql);
    		System.out.println("here");
    		ResultSet rs = ps.executeQuery();
    		System.out.println("here3");
    		if(rs.next()){
    			System.out.println("here2");
    			return true;
    		}
    	}catch(SQLException e){
    		System.out.println("Opening question failed!");
    		e.printStackTrace();
    	}
    	return false;
    }
    
    /**
     * @return a string array of QuestionIDs associated with the given pollID 
     * @param PollID the id of the poll to retrieve questions for.
     */
    private ArrayList<String> getPollQuestions(int PollID){
    	ArrayList<String> questions = new ArrayList<String>();
    	String sql = "SELECT QuestionID from Poll_Question WHERE PollID="+PollID;
    	
    	try{
    		PreparedStatement ps = conn.getConn().prepareStatement(sql);
    		ResultSet rs = ps.executeQuery();
    		while(rs.next()){
    			questions.add(rs.getString("QuestionID"));
    		}
    	}catch(SQLException e){
    		System.out.println("getPollQuestions failed!");
    	}
    	return questions;
    }
    
    /**
     * @return the ID of the open question in a poll, if any. If none, returns -1
     * @param QuestionID the ID of the question to check
     */
    private int hasOpenQuestion(int PollID){
    	int question = -1;
    	String sql = "SELECT Question.QuestionID FROM Question, Poll_Question WHERE Question.Status=1 AND Poll_Question.PollID="+PollID;
    	
    	try{
    		PreparedStatement ps = conn.getConn().prepareStatement(sql);
    		ResultSet rs = ps.executeQuery();
    		if(rs.next()){
    				question = rs.getInt(1);
    				return question;
    		}
    	}catch(SQLException e){
    		System.out.println("hasOpenQuestion failed!");
    		e.printStackTrace();
    	}
    	return question;
    }
    
    /**
     * @return a Question bean containing all columns available on the given question
     * @param qID the ID of the question to get details on
     * TODO: complete
     */
    private Question getQuestion(int qID){
    	Question question = new Question();
    	String sql = "SELECT * FROM Question WHERE QuestionID="+qID;
    	try{
    		PreparedStatement ps = conn.getConn().prepareStatement(sql);
    		ResultSet rs = ps.executeQuery();
    		if(rs.next()){
    			question.setQuestionID(rs.getInt("QuestionID"));
    			question.setText(rs.getString("Text"));
    			question.setType(rs.getString("Type"));
    			question.setStatus(rs.getInt("Status"));
    			question.setCharStyles(rs.getString("ChartStyles"));
    			question.setChartColor(rs.getString("ChartColor"));
    			question.setColor(rs.getString("Color"));
    			question.setTimer(rs.getString("Timer"));
    			question.setFont(rs.getString("Font"));
    			question.setCorrectAnswer(rs.getInt("CorrectAnswer"));
    			question.setCAI(rs.getString("CAI"));
    			question.setHighest(rs.getDouble("Highest"));
    			question.setLowest(rs.getDouble("Lowest"));
    			question.setFontSize(rs.getInt("FontSize"));
    			question.setResCounter(rs.getString("ResCounter"));
    		}
    	}catch(SQLException e){
    		System.out.println("getQuestion failed!");
    	}
    	return question;
    }
    
    
    private void initReceivers() {
        try {
            receiverListModel.addAll(ReceiverService.findReceivers());
        } catch (Exception e) {
            showError("Could not initialize receivers.", e);
        }
        dataset = createDataset();
    }

    private void initModel() {
        //responseChart.setDataset(dataset);

        responseList.setModel(responseListModel);
        receiverList.setModel(receiverListModel);
        receiverList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) {
                    return;
                }
                int selection = receiverList.getSelectedIndex();
                try {
                    Receiver receiver = receiverListModel.get(selection);
                    lblChannel.setText(Integer.toString(receiver.getChannel()));
                    lblDescription.setText(receiver.getDescription());
                    lblId.setText(receiver.getId());
                    lblId1.setText(receiver.getVersion());
                } catch (Exception ex) {
                    //ignore
                }

            }
        });
        receiverList.setCellRenderer(receiverCellRenderer);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        receiverList = new javax.swing.JList();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        lblDescription = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblChannel = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lblId = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        lblId1 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        responseList = new javax.swing.JList();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        mnuRefresh = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        mnuStart2 = new javax.swing.JMenuItem();
        mnuStart1 = new javax.swing.JMenuItem();
        mnuStart4 = new javax.swing.JMenuItem();
        mnuStart5 = new javax.swing.JMenuItem();
        mnuStart6 = new javax.swing.JMenuItem();
        mnuStart7 = new javax.swing.JMenuItem();
        mnuStart8 = new javax.swing.JMenuItem();
        mnuStart9 = new javax.swing.JMenuItem();
        mnuStart10 = new javax.swing.JMenuItem();
        mnuStart11 = new javax.swing.JMenuItem();
        mnuStart13 = new javax.swing.JMenuItem();
        mnuStop = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ResponseCardSDK Demo App");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                ResponseCardInterface.this.windowClosing(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Receivers"));

        receiverList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        receiverList.setComponentPopupMenu(jPopupMenu1);
        jScrollPane1.setViewportView(receiverList);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 341, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 97, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Receiver Info"));

        jLabel1.setText("Description:");

        lblDescription.setText("N/A");

        jLabel3.setText("Channel:");

        lblChannel.setText("N/A");

        jLabel2.setText("Id:");

        lblId.setText("N/A");

        jLabel4.setForeground(new java.awt.Color(204, 0, 0));
        jLabel4.setText("Firmware:");

        lblId1.setText("N/A");

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1)
                    .add(jLabel3)
                    .add(jLabel2)
                    .add(jLabel4))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(lblId1)
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(lblChannel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
                        .add(99, 99, 99))
                    .add(lblDescription, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
                    .add(lblId))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblDescription, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblChannel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblId)
                    .add(jLabel2))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(lblId1))
                .addContainerGap(204, Short.MAX_VALUE))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Poll Results"));

        jScrollPane2.setViewportView(responseList);

        org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE)
        );

        jMenu1.setText("File");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Quit");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitActionHandler(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Poll");

        mnuRefresh.setText("Refresh Receiver List");
        mnuRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshReceiverHandler(evt);
            }
        });
        jMenu2.add(mnuRefresh);
        jMenu2.add(jSeparator1);

        mnuStart2.setText("SingleResponse_Alpha");
        mnuStart2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        jMenu2.add(mnuStart2);

        mnuStart1.setText("SingleResponse_Numeric");
        mnuStart1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        jMenu2.add(mnuStart1);

        mnuStart4.setText("MultiResponse_Alpha");
        mnuStart4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        jMenu2.add(mnuStart4);

        mnuStart5.setText("MultiResponse_Numeric");
        mnuStart5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        jMenu2.add(mnuStart5);

        mnuStart6.setText("MultiResponse_NoDuplicates");
        mnuStart6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        jMenu2.add(mnuStart6);

        mnuStart7.setText("MultiResponse_NoDuplicates_Alpha");
        mnuStart7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        jMenu2.add(mnuStart7);

        mnuStart8.setText("MultiResponse_NoDuplicates_Numeric");
        mnuStart8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        jMenu2.add(mnuStart8);

        mnuStart9.setText("ShortAnswer");
        mnuStart9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        jMenu2.add(mnuStart9);

        mnuStart10.setText("Numeric");
        mnuStart10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        jMenu2.add(mnuStart10);

        mnuStart11.setText("Essay");
        mnuStart11.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        jMenu2.add(mnuStart11);

        mnuStart13.setText("InvalidResponse");
        mnuStart13.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startPollHandler(evt);
            }
        });
        jMenu2.add(mnuStart13);

        mnuStop.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        mnuStop.setText("Stop Poll (All Receivers)");
        mnuStop.setEnabled(false);
        mnuStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopPollHandler(evt);
            }
        });
        jMenu2.add(mnuStop);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jPanel1, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 127, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitActionHandler(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionHandler
        try {
            poll.shutdown();
        } catch (Exception ex) {
            Logger.getLogger(ResponseCardInterface.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.exit(0);
    }//GEN-LAST:event_exitActionHandler

    private void startPollHandler(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startPollHandler
        //this.responseChart.setDataset((dataset = createDataset()));
        this.responseListModel.clear();
        try {//System.out.println("evt paramString: " + evt.getActionCommand());
            //see if it's an invalid response poll that we're starting
            if (evt.getActionCommand().equals("InvalidResponse")) {
                String answerRange = "246809";
                poll = PollService.createCorrectPoll(evt.getActionCommand(), answerRange);          
            }else{
                poll = PollService.createPoll();                
            }
            poll.addResponseListener(new BasicResponseListener());
            Poll.PollingMode pollingMode = (Poll.PollingMode.valueOf(evt.getActionCommand()));
            poll.start(pollingMode);
            
            mnuRefresh.setEnabled(false);
               mnuStart2.setEnabled(true);
               mnuStart1.setEnabled(true);
               mnuStart4.setEnabled(true);
               mnuStart5.setEnabled(true);
               mnuStart6.setEnabled(true);
               mnuStart7.setEnabled(true);
               mnuStart8.setEnabled(true);
               mnuStart9.setEnabled(true);
               mnuStart10.setEnabled(true);
               mnuStart11.setEnabled(true);               
               mnuStart13.setEnabled(true);
            if (evt.getActionCommand().equals("SingleResponse_Alpha")) {
               mnuStart2.setEnabled(false);
            }else if (evt.getActionCommand().equals("SingleResponse_Numeric")) {
               mnuStart1.setEnabled(false);
            }else if (evt.getActionCommand().equals("MultiResponse_Alpha")) {
               mnuStart4.setEnabled(false);
            }else if (evt.getActionCommand().equals("MultiResponse_Numeric")) {
               mnuStart5.setEnabled(false);
            }else if (evt.getActionCommand().equals("MultiResponse_NoDuplicates")) {
               mnuStart6.setEnabled(false);
            }else if (evt.getActionCommand().equals("MultiResponse_NoDuplicates_Alpha")) {
               mnuStart7.setEnabled(false);
            }else if (evt.getActionCommand().equals("MultiResponse_NoDuplicates_Numeric")) {
               mnuStart8.setEnabled(false);
            }else if (evt.getActionCommand().equals("ShortAnswer")) {
               mnuStart9.setEnabled(false);
            }else if (evt.getActionCommand().equals("Numeric")) {
               mnuStart10.setEnabled(false);
            }else if (evt.getActionCommand().equals("Essay")) {
               mnuStart11.setEnabled(false);            
            }else if (evt.getActionCommand().equals("InvalidResponse")) {
               mnuStart13.setEnabled(false);
            }
            mnuStop.setEnabled(true);

            //responseChart.setSubtitle(evt.getActionCommand() + " Polling Open");
        } catch (Exception e) {
            showError("Unable to start poll.", e);
        }
    }//GEN-LAST:event_startPollHandler

    private void stopPollHandler(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopPollHandler
        try {
            poll.stop();
            mnuRefresh.setEnabled(true);
            mnuStart1.setEnabled(true);
            mnuStart2.setEnabled(true);
            mnuStart4.setEnabled(true);
            mnuStart5.setEnabled(true);
            mnuStart6.setEnabled(true);
            mnuStart7.setEnabled(true);
            mnuStart8.setEnabled(true);
            mnuStart9.setEnabled(true);
            mnuStart10.setEnabled(true);
            mnuStart11.setEnabled(true);            
            mnuStart13.setEnabled(true);
            mnuStop.setEnabled(false);
            //responseChart.setSubtitle("Polling Closed");
        } catch (Exception e) {
            showError("Unable to stop poll.", e);
        }
    }//GEN-LAST:event_stopPollHandler

	private void refreshReceiverHandler(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshReceiverHandler
            receiverListModel.clear();
            responseListModel.clear();
            try {
                int selectedIndex = receiverList.getSelectedIndex();
                receiverListModel.addAll(ReceiverService.findReceivers());
                receiverList.clearSelection();
                if (receiverList.getModel().getSize() > 0) {
                    if (receiverList.getModel().getSize() > selectedIndex && selectedIndex > -1)
                        receiverList.setSelectedIndex(selectedIndex);
                    else
                        receiverList.setSelectedIndex(0);
                }
            } catch (Exception ex) {
                showError("Unable to initialize receivers.", ex);
            }
            //this.responseChart.setDataset((dataset = createDataset()));
    }//GEN-LAST:event_refreshReceiverHandler

private void windowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_windowClosing
    try {
        if (poll != null) {
            poll.shutdown();
        } else {
            List<Receiver> receivers = receiverListModel.getReceivers();
            for (Receiver receiver : receivers) {
                receiver.close();
            }
        }
        } catch (Exception ex) {//GEN-LAST:event_windowClosing
            Logger.getLogger(ResponseCardInterface.class.getName()).log(Level.SEVERE, "There was a problem shutting down the poll.", ex);
        }
    }

    private void showError(String message, Exception e) {
        JOptionPane.showMessageDialog(null, message + "\n Reason:" + e.getMessage());
    }

    
    public static boolean makeDBLoginDialog(){
    	JDialog loginDialog = new JDialog();
    	loginDialog.setAlwaysOnTop(true);
    	loginDialog.setEnabled(true);
    	
    	JTextArea usernameText = new JTextArea();
    	JTextArea passwordText = new JTextArea();
    	JButton submitButton = new JButton();
    	JButton cancelButton = new JButton();
    	usernameText.setText("Username:");
    	usernameText.setVisible(true);
    	
    	loginDialog.getContentPane().add(usernameText);
    	loginDialog.getContentPane().add(passwordText);
    	loginDialog.getContentPane().add(submitButton);
    	loginDialog.getContentPane().add(cancelButton);
    	loginDialog.pack();
    	loginDialog.paint(loginDialog.getGraphics());
    	loginDialog.setVisible(true);
    	return false;
    }
        
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /**if (args.length != 2) {
            System.out.println("Usage: PollingTest [company name] [license key]");
            System.exit(0);

        }*/
        System.setProperty("apple.laf.useScreenMenuBar", "true");
        ResponseCardLibrary.turnDebuggingOn();

       ResponseCardLibrary.initializeLicense(
    		   "University of Queensland", 
               "24137BBFEEEA9C7F5D65B2432F10F960");
       
       
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    UIManager.setLookAndFeel(
                            UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {/*ignore*/

                }
                try {
					new ResponseCardInterface().setVisible(true);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblChannel;
    private javax.swing.JLabel lblDescription;
    private javax.swing.JLabel lblId;
    private javax.swing.JLabel lblId1;
    private javax.swing.JMenuItem mnuRefresh;
    private javax.swing.JMenuItem mnuStart1;
    private javax.swing.JMenuItem mnuStart10;
    private javax.swing.JMenuItem mnuStart11;
    private javax.swing.JMenuItem mnuStart13;
    private javax.swing.JMenuItem mnuStart2;
    private javax.swing.JMenuItem mnuStart4;
    private javax.swing.JMenuItem mnuStart5;
    private javax.swing.JMenuItem mnuStart6;
    private javax.swing.JMenuItem mnuStart7;
    private javax.swing.JMenuItem mnuStart8;
    private javax.swing.JMenuItem mnuStart9;
    private javax.swing.JMenuItem mnuStop;
    private javax.swing.JList receiverList;
    private javax.swing.JList responseList;
    // End of variables declaration//GEN-END:variables

    private DefaultCategoryDataset createDataset() {
        DefaultCategoryDataset newDataset = new DefaultCategoryDataset();
        List<Receiver> receivers = receiverListModel.getReceivers();
        for (Receiver receiver : receivers) {
            for (int i = 0; i < 10; i++) {
                newDataset.addValue(0, receiver.getId(), Integer.toString(i));
            }
        }

        return newDataset;

    }

    private class ReceiverListModel extends DefaultListModel {
        private List<Receiver> receivers = new ArrayList();

        @Override
        public void clear() {
            receivers.clear();
            fireContentsChanged(this, 0, 0);
        }

        public void addAll(Collection newData) {
            receivers.addAll(newData);
            fireContentsChanged(this, 0, 0);
        }

        @Override
        public int getSize() {
            return receivers.size();
        }

        @Override
        public Object getElementAt(int index) {
            return receivers.get(index);
        }

        @Override
        public Receiver get(int index){
            return receivers.get(index);
        }

        public List<Receiver> getReceivers(){
            return receivers;
        }
    }

    private class ReceiverListCellRenderer extends JLabel implements ListCellRenderer {

        public Component getListCellRendererComponent(JList list, Object value,
                int index, boolean isSelected, boolean cellHasFocus) {

            Receiver r = receiverListModel.get(index);

            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            setOpaque(true);
            setText(r.getId());

            return this;
        }
    }

    private class ResponseListModel extends DefaultListModel {
        List<Response> responses = new ArrayList();

        @Override
        public void clear() {
            responses.clear();
            fireContentsChanged(this, 0, 0);
        }

        public void add(Response newData) {
            responses.add(newData);
            fireContentsChanged(this, getSize()-2, getSize()-1);
        }

        @Override
        public int getSize() {
            return responses.size();
        }

        @Override
        public Object getElementAt(int index) {
            return responses.get(index);
        }
    }

    private class BasicResponseListener implements ResponseListener {

        public BasicResponseListener() {
        }

        public void responseReceived(Response response) {            
            responseListModel.add(response);            
            if (response.getReceiverId() == null ||
                    response.getResponse() == null ||
                    response.getResponse().equals("?")) {
                return;
            }

//            if (!dataset.getColumnKeys().contains(response.getResponse()))
                
            /**
            Number count = dataset.getValue(response.getReceiverId(), response.getResponse());
            if (count == null) {
                count = new Integer(1);
            }
            */
            //dataset.incrementValue(1, response.getReceiverId(), response.getResponse());
        }
    }

    private class SetChannelAction extends AbstractAction {

        public SetChannelAction() {
            putValue(Action.NAME, "Set Channel");
            putValue(Action.LONG_DESCRIPTION, "Set Channel");
        }

        public void actionPerformed(ActionEvent arg0) {
            try {

                int index =
                        receiverList.getSelectionModel().getAnchorSelectionIndex();
                if (index < 0) {
                    return;
                }
                List<Receiver> receivers = receiverListModel.getReceivers();
                Receiver r = receivers.get(index);
                String channel = JOptionPane.showInputDialog("Please enter the new channel:");
                if (channel == null) {
                    return;
                }
                r.setChannel(Integer.parseInt(channel));
                lblChannel.setText(Integer.toString(r.getChannel()));

            } catch (Exception ex) {
                Logger.getLogger(ResponseCardInterface.class.getName()).log(
                        Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(null, "Could not set the channel.");
            }
        }
    }
}
